package com.programming.forum.controller;

import com.programming.forum.common.AppResult;
import com.programming.forum.common.ResultCode;
import com.programming.forum.config.AppConfig;
import com.programming.forum.dao.MessageMapper;
import com.programming.forum.exception.ApplicationException;
import com.programming.forum.model.Message;
import com.programming.forum.model.User;
import com.programming.forum.services.IMessageService;
import com.programming.forum.services.IUserService;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-11-14
 * Time: 18:49
 */
@Api(tags = "站内信接口")
@RequestMapping("/message")
@RestController
@Slf4j
public class MessageController {

    @Resource
    private IUserService userService;
    @Resource
    private IMessageService messageService;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("接收方Id") @RequestParam("receiveUserId") @NotNull Long receiveUserId,
                            @ApiParam("内容") @RequestParam("content") @NotNull String content) {

        //检验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            //用户已禁言 FAILED_USER_BANNED      (1103,"您已被禁言, 请联系管理员, 并重新登录."),
            return AppResult.failed(ResultCode.FAILED_USER_BANNED );
        }
        //不能给自己发站内信
        if(user.getId() == receiveUserId) {
            return AppResult.failed("不能给自己发站内信");
        }
        //校验接受者是否存在
        User receiveUser = userService.selectById(receiveUserId);
        if(receiveUser == null) {
            //FAILED_USER_NOT_EXISTS  (1102,"用户不存在"),
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 4. 封装对象
        Message message = new Message();
        message.setPostUserId(user.getId()); // 发送者Id
        message.setReceiveUserId(receiveUserId); // 接收者Id
        message.setContent(content); // 站内信的内容
        // 5. 调用Service
        messageService.create(message);
        // 6. 返回结果
        return AppResult.success("发送成功");
    }


    @ApiOperation("获取未读数")
    @GetMapping("getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        //检验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Integer count = messageService.selectUnReadCount(user.getId());
        return AppResult.success(count);
    }


    @ApiOperation("获取站内信列表")
    @GetMapping("/getAll")
    public AppResult getAll(HttpServletRequest request) {
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用Service
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());

        return AppResult.success(messages);
    }

    @PostMapping("/markRead")
    @ApiOperation(("更新为已读"))
    public AppResult markRead(HttpServletRequest request,
            @ApiParam("站内信Id") @RequestParam("id") @NotNull Long id) {
        //根据Id查询站内信
        Message message = messageService.selectById(id);
        //站内信是否存在
        if(message == null || message.getDeleteState() == 1) {
            //FAILED_MESSAGE_NOT_EXISTS      (1401,"站内信不存在"),
           return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //站内是不是自己的
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getId() != message.getReceiveUserId()) {
            //FAILED_FORBIDDEN        (1003, "禁止访问"),
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN );
        }
        //调用service 状态更新为已读
        messageService.updateStateById(id, (byte) 1);
        return AppResult.success();
    }

    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("被回复站内信Id") @RequestParam("repliedId") @NotNull Long repliedId,
                           @ApiParam("内容") @RequestParam("content") @NotNull String content) {
        //检验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            //用户已禁言 FAILED_USER_BANNED      (1103,"您已被禁言, 请联系管理员, 并重新登录."),
            return AppResult.failed(ResultCode.FAILED_USER_BANNED );
        }

        //校验要回复的站内信状态
        Message existsMessage = messageService.selectById(repliedId);
        if(existsMessage == null || existsMessage.getDeleteState() == 1) {
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS);
        }
        //不能给自己回复站内信
        if(user.getId() == existsMessage.getPostUserId()) {
            return AppResult.failed("不能给自己发站内信");
        }
        //构造对象
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId((existsMessage.getPostUserId()));
        message.setContent(content);
        //调用service
        messageService.reply(repliedId,message);
        return AppResult.success();
    }
}
